package com.slipper.system.codeless.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slipper.common.service.CommonService;
import com.slipper.exception.CommonException;
import com.slipper.system.codeless.bo.ColumnBO;
import com.slipper.util.BeanUtil;
import com.slipper.util.DatabaseUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.codeless.dao.DatabaseDao;
import com.slipper.system.codeless.bo.DatabaseBO;

import com.slipper.core.transaction.ReadTransactional;

@Service
@ReadTransactional
public class DatabaseService {
    @Resource
    private DatabaseDao databaseDao;
    @Resource
    private CommonService commonService;

    public DatabaseBO queryDatabase() {
        String dbType = DatabaseUtil.getType();
        DatabaseBO database = databaseDao.queryByType(dbType);
        if (database == null) throw new CommonException("找不到与数据库类型[" + dbType + "]相关的数据库配置信息！");
        return database;
    }

    public List<ColumnBO> queryColumnList(String tableName, String queryColumnSql) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sql", queryColumnSql.replace("{tableName}", tableName));
        List<Map<String, Object>> resultList = commonService.queryList(paramMap);
        return BeanUtil.toList(resultList, ColumnBO.class);
    }

    public DatabaseBO queryBy(String id) {
        return databaseDao.queryBy(id);
    }

    public PageInfo<DatabaseBO> queryPage(DatabaseBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(databaseDao.queryList(bo));
    }

}
